<?php

namespace app\admin\model;

use think\Model;

use think\Db;
use think\Request;

class Sale_invoice extends Model
{
    /*
     * 开票员发票 sale_invoice
     */
    public function getsaleinvoice($res)
    {
        $page = $res['page'];
        $limit = $res['pageSize'];
        if (isset($res['dname']) && $res['dname']) {
            //公司名查询
            $companyname = array_column(model('company')->getcompanyname($res), 'id');
            if ($companyname) {
                $maps['b.co_id'] = array('in', $companyname);
                $maps['b.co_branch_id'] = array('in', $companyname);
            }
            $maps['a.sale_id'] = array('like', '%' . removeBlank($res['dname']) . '%');//订单号
        } else {
            $maps = array();
        }
        $reswhere = $this->statuswhere($res['status']);
        $salewhere = $reswhere['salewhere'];
        $join = [
            ['sale b', 'a.sale_id=b.id', 'LEFT'],//销售表
            ['sale_make c', 'b.id=c.sale_id', 'LEFT'],//配货表
            ['sale_invoice_type d', 'a.invoice_type_id=d.id', 'LEFT'],//发票类型表
        ];
        $saledata = Db::name('sale_invoice')->alias('a')->join($join)->where(function ($query) use ($salewhere) {
            $query->where($salewhere);
        })->where(function ($query) use ($maps) {
            $query->whereOr($maps);
        })->field('a.*,b.priority,b.co_id,b.co_branch_id,b.pay,b.saler_id,c.package_at as start_at,d.code')->page($page, $limit)->select();

        $count = Db::name('sale_invoice')->alias('a')->join($join)->where(function ($query) use ($salewhere) {
            $query->where($salewhere);
        })->where(function ($query) use ($maps) {
            $query->whereOr($maps);
        })->count();

        foreach ($saledata as $saledatakey => $saledataval) {
            //设置间隔时间
            $timedate = gettime($saledataval['start_at'], time());
            $saledata[$saledatakey]['interval_time'] = $timedate['hour'] . ":" . $timedate['min'] . ':' . $timedate['sec'];
            //公司名称
            $saledata[$saledatakey]['company_name'] = getinfo($saledataval['co_id'], 'company')['name'];
            $saledata[$saledatakey]['company_branch_name'] = getinfo($saledataval['co_branch_id'], 'co_branch')['name'];
            //业务员
            $saledata[$saledatakey]['saler_name'] = getinfo($saledataval['saler_id'], 'admin')['nickname'];
            //编辑者编辑时间
            $saledata[$saledatakey]['managename'] = getinfo($saledataval['update_id'], 'admin')['nickname'];
            $saledata[$saledatakey]['update_date'] = getTimeDate($saledataval['update_at'], 12);

            //开票人 开票时间
            $saledata[$saledatakey]['drawername'] = getinfo($saledataval['drawer_id'], 'admin')['nickname'];
            if ($saledataval['drawer_at'] > 0) {
                $saledata[$saledatakey]['drawer_date'] = getTimeDate($saledataval['drawer_at'], 12);
            }
            //发票号
            if ($saledataval['number']) {
                $saledata[$saledatakey]['number'] = implode(' ', str_split($saledataval['number'], 4));
            }
            //处理一个销售订单对应多个备注
            $saledata[$saledatakey]['remark'] = getables('sale_remark', ['sale_id' => $saledataval['sale_id']], 'id,remark');
        }
        //处理每一个标签的数字
        $arrcount = $this->arrcount($join, $maps, $res['status']);
        return array('count' => $count, 'data' => $saledata, 'arrcount' => $arrcount);
    }

    //设置的是每一个标签的条件
    protected function statuswhere($status)
    {
        $endToday = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
        //7天之前的时间
        $sevenday = mktime(0, 0, 0, date('m'), date('d') - 7, date('Y')) - 1;
        $mapwhere = array();
        $mapwhere['a.invoice_type_id'] = array('gt', 0);//发票类型ID>0
        switch ($status) {
            case '1':
                //待开票
                $mapwhere['a.number'] = ['eq', ''];//还未填写订单发票号
                $mapwhere['b.del_at'] = 0;//销售表（没有删除）
                $mapwhere['c.package_at'] = array('gt', 0);//装箱录入完成
                break;
            case '2':
                //已完成
                $mapwhere['a.number'] = ['neq', ''];//已经填写发票
                $mapwhere['a.drawer_at'] = ['between', "$sevenday,$endToday"];//查看7天以内的开票数据
                $mapwhere['a.del_at'] = 0;//没有删除
                $mapwhere['b.del_at'] = 0;//销售表
                break;
            case '3':
                //已取消
                $mapwhere['a.del_at'] = 0;//发票表
                $mapwhere['a.number'] = ['neq', ''];//没有填写发票号
                $mapwhere['b.del_at'] = array('gt', 0);//销售表
                break;
            case '4':
                //已删除
                $mapwhere['a.number'] = ['neq', ''];//发票表
                $mapwhere['a.del_at'] = array('gt', 0);//发票表
                break;
        }
        return array('salewhere' => $mapwhere);
    }

    /*
     * 计算每一个标签的数据
     */
    protected function arrcount($join, $maps, $status)
    {
        $ones = $twos = $threes = $fours = array();
        switch ($status) {
            case '1':
                $ones = $maps;
                break;
            case '2':
                $twos = $maps;
                break;
            case '3':
                $threes = $maps;
                break;
            case '4':
                $fours = $maps;
                break;
        }
        $reswhereone = $this->statuswhere(1)['salewhere'];
        $reswheretwo = $this->statuswhere(2)['salewhere'];
        $reswherethree = $this->statuswhere(3)['salewhere'];
        $reswherefour = $this->statuswhere(4)['salewhere'];


        $one = Db::name('sale_invoice')->alias('a')->join($join)->where(function ($query) use ($reswhereone) {
            $query->where($reswhereone);
        })->where(function ($query) use ($maps) {
            $query->whereOr($maps);
        })->count();

        $two = Db::name('sale_invoice')->alias('a')->join($join)->where(function ($query) use ($reswheretwo) {
            $query->where($reswheretwo);
        })->where(function ($query) use ($maps) {
            $query->whereOr($maps);
        })->count();

        $three = Db::name('sale_invoice')->alias('a')->join($join)->where(function ($query) use ($reswherethree) {
            $query->where($reswherethree);
        })->where(function ($query) use ($maps) {
            $query->whereOr($maps);
        })->count();

        $four = Db::name('sale_invoice')->alias('a')->join($join)->where(function ($query) use ($reswherefour) {
            $query->where($reswherefour);
        })->where(function ($query) use ($maps) {
            $query->whereOr($maps);
        })->count();
        return array(
            'one' => $one == 0 ? '' : $one,
            'two' => $two == 0 ? '' : $two,
            'three' => $three == 0 ? '' : $three,
            'four' => $four == 0 ? '' : $four,
        );
    }

    //点击开发票数据的获取 开发票  编辑 查看  按钮的数据获取
    public function codeinvoice($res)
    {
        $join = [
            ['sale b', 'a.sale_id=b.id', 'LEFT'],//销售表
            ['sale_invoice_type c', 'a.invoice_type_id=c.id', 'LEFT'],//发票类型表
        ];
        $mapwhere['a.id'] = $res['id'];
        $mapwhere['a.invoice_type_id'] = array('gt', 0);//发票类型ID>0
        $leftdata = Db::name('sale_invoice')->alias('a')->join($join)->field('a.*,b.co_id,b.co_branch_id,c.code')->where($mapwhere)->find();

        $companyinfo = getinfo($leftdata['co_id'], 'company');
        $combranchinfo = getinfo($leftdata['co_branch_id'], 'co_branch');
        $leftdata['company_name'] = $companyinfo['name'];
        $leftdata['regno'] = $companyinfo['regno'];
        $leftdata['taxno'] = $companyinfo['taxno'];
        $leftdata['co_branch_name'] = $combranchinfo['name'];
        $leftdata['regnos'] = $combranchinfo['regno'];
        $leftdata['taxnos'] = $combranchinfo['taxno'];
        $del_name = $del_date = $upl_name = $upl_date = $drawername = $drawertime = '';
        if ($leftdata['drawer_id'] > 0) {
            $drawername = getinfo($leftdata['drawer_id'], 'admin')['nickname'];
            $drawertime = getTimeDate($leftdata['drawer_at'], 12);
        }
        //开票人和开票时间
        $leftdata['drawername'] = $drawername;
        $leftdata['drawertime'] = $drawertime;

        if ($leftdata['update_id'] > 0) {
            $upl_name = getinfo($leftdata['update_id'], 'admin')['nickname'];//更新人
            $upl_date = getTimeDate($leftdata['update_at'], 12);//更新时间
        }
        //更新人和更新时间
        $leftdata['upl_name'] = $upl_name;
        $leftdata['upl_date'] = $upl_date;

        if ($leftdata['del_id'] > 0) {
            $del_name = getinfo($leftdata['del_id'], 'admin')['nickname'];//删除人
            $del_date = getTimeDate($leftdata['del_at'], 12);//删除时间
        }
        //删除人和删除时间
        $leftdata['del_name'] = $del_name;
        $leftdata['del_date'] = $del_date;
        //销售的产品数据
        $rightdata = Db::name('sale_detail')->where('sale_id', $leftdata['sale_id'])->select();
        foreach ($rightdata as $rightdatakey => $rightdataval) {
            //产品数据
            $rightdata[$rightdatakey]['pro_data'] = getProAndProchar($rightdataval, $res['lang'], 48);
        }
        return array('leftdata' => $leftdata, 'rightdata' => $rightdata);
    }

    /*
     * 开发票保存点击
     */
    public function savedatainvoice($res)
    {
        $id = $res['leftdata']['id'];
        if (!$res['leftdata']['number']) {
            return array('msg' => '请填写订单发票号', 'status' => 2);
        }
        //更新这个发票登记表
        $update['number'] = $res['leftdata']['number'];
        $update['update_id'] = $update['drawer_id'] = session('userid');
        $update['update_at'] = $update['drawer_at'] = time();
        $upid = Db::name('sale_invoice')->where('id', $id)->update($update);
        if ($upid !== false) {
            return array('msg' => lang("edited_successfully"), 'status' => 1);
        } else {
            return array('msg' => lang("edit_failed"), 'status' => 0);
        }

    }

    /*
     * 已完成中的删除点击
     * 已取消中的删除点击
     * 已删除中的恢复点击
     */
    public function delresumeinvoice($res, $code)
    {
        if ($code == 1 || $code == 2) {
            //已完成 已取消中的取消
            $del_data['del_id'] = session('userid');
            $del_data['del_at'] = time();
            $delid = Db::name('sale_invoice')->where('id', $res['id'])->update($del_data);
            if ($delid) {
                return array('msg' => $res['sale_id'] . lang("deleted_successfully"), 'status' => 1);
            } else {
                return array('msg' => $res['sale_id'] . lang("failed_to_delete"), 'status' => 0);
            }
        } elseif ($code == 3) {
            //恢复的处理
            $del_data['update_id'] = session('userid');
            $del_data['update_at'] = time();
            $del_data['del_at'] = $del_data['del_id'] = 0;
            $delid = Db::name('sale_invoice')->where('id', $res['id'])->update($del_data);
            //通过id去查找sale表的中del_id
            $sale_id = getValue('sale_invoice', ['id' => $res['id']], 'sale_id');
            //恢复销售表中的del_at del_id
            Db::name('sale')->where('id', $sale_id)->update(['del_id' => 0, 'del_at' => 0]);
            if ($delid) {
                return array('msg' => $res['sale_id'] . '恢复成功', 'status' => 1);
            } else {
                return array('msg' => $res['sale_id'] . '恢复失败', 'status' => 0);
            }
        }

    }
}